package com.ry.executor;

import java.io.IOException;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

//自定义线程池
public class ExecutorExp {

    public static void main(String[] args) throws InterruptedException, IOException {
        int corePoolSize = 2;
        int maximunPoolSize = 4;
        long keepAliveTime = 10;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(2);
        ThreadFactory threadFactory = new NameThreadFactory();
        RejectedExecutionHandler handler = new MyIgnorePolicy();
        ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize,maximunPoolSize,keepAliveTime,unit,workQueue,threadFactory,handler);
        executor.prestartCoreThread();//预启动所有核心线程

        for (int i = 1; i <= 10 ; i++) {
            MyTask task = new MyTask(String.valueOf(i));
            executor.execute(task);
        }
    }

    static class NameThreadFactory implements ThreadFactory{

        private final AtomicInteger mThreadNum = new AtomicInteger(1);

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r,"my-thread-"+ mThreadNum.getAndIncrement());
            System.out.println(t.getName() + " has been created");
            return t;
        }
    }


    public static class MyIgnorePolicy implements RejectedExecutionHandler{
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            //记录日志
            System.out.println(r.toString() + " rejected");

        }
    }

    static class MyTask implements Runnable {
        private String name;

        public MyTask(String name){
            this.name = name;
        }

        @Override
        public void run() {
            try{
                System.out.println(this.toString() + " is running!");
                Thread.sleep(3000);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }

        public String  getName(){
            return name;
        }

        @Override
        public String toString(){
            return "MyTask [name=" + name +"]";
        }
    }
}
